import React  from 'react';
import PropTypes from 'proptypes';
import debounce from 'lodash/debounce';
import AceEditor from 'react-ace';
import ace from 'brace';

import 'brace/mode/sql';
import 'brace/theme/clouds_midnight';
import 'brace/ext/language_tools';
import 'brace/ext/searchbox';

import Button from '@mui/material/Button';
import Toolbar from '@mui/material/Toolbar';
import QueryResult from './query-result.jsx';
import ServerDBClientInfoModal from './server-db-client-info-modal.jsx';

const QUERY_EDITOR_HEIGTH = 200;
// const langTools = ace.acequire('ace/ext/language_tools');

const INFOS = {
  mysql: [
    'MySQL treats commented query as a non select query.' +
      'So you may see "affected rows" for a commented query.',
    'Usually executing a single query per tab will give better results.',
  ],
  sqlserver: [
    'MSSQL treats multiple non select queries as a single query result.' +
      'So you affected rows will show the amount over all queries executed in the same tab.',
    'Usually executing a single query per tab will give better results.',
  ],
};

const EVENT_KEYS = {
  onSelectionChange: 'changeSelection',
};

export default function Query(props){
  console.log("functin Query=============");
  console.log(props);
  const queryBoxTextarea=React.useRef(null);
  // static propTypes = {
  //   widthOffset: PropTypes.number.isRequired,
  //   client: PropTypes.string.isRequired,
  //   allowCancel: PropTypes.bool.isRequired,
  //   query: PropTypes.object.isRequired,
  //   enabledAutoComplete: PropTypes.bool.isRequired,
  //   enabledLiveAutoComplete: PropTypes.bool.isRequired,
  //   databases: PropTypes.array,
  //   tables: PropTypes.array,
  //   columnsByTable: PropTypes.object,
  //   triggersByTable: PropTypes.object,
  //   indexesByTable: PropTypes.object,
  //   views: PropTypes.array,
  //   functions: PropTypes.array,
  //   procedures: PropTypes.array,
  //   onExecQueryClick: PropTypes.func.isRequired,
  //   onCancelQueryClick: PropTypes.func.isRequired,
  //   onCopyToClipboardClick: PropTypes.func.isRequired,
  //   onSaveToFileClick: PropTypes.func.isRequired,
  //   onSQLChange: PropTypes.func.isRequired,
  //   onSelectionChange: PropTypes.func.isRequired,
  //   editorName: PropTypes.string.isRequired,
  // };

    const [state,setState]=React.useState({
      query_height: QUERY_EDITOR_HEIGTH,
      wrapEnabled: false,
    });
  
  // React.useEffect(()=>{
  //   queryBoxTextarea.current.editor.on(
  //     EVENT_KEYS.onSelectionChange,
  //     debounce(onSelectionChange, 100)
  //   );

  //   // init with the auto complete disabled
  //   queryBoxTextarea.current.editor.completers = [];
  //   queryBoxTextarea.current.editor.setOption(
  //     'enableBasicAutocompletion',
  //     false
  //   );
  // },[])
  //will receive props
  // {
  //   const completions = getQueryCompletions(nextProps);

  //   const customCompleter = {
  //     getCompletions(editor, session, pos, prefix, callback) {
  //       callback(null, completions);
  //     },
  //   };

  //   // force load only the current available completers
  //   // discarding any previous existing completers
  //   queryBoxTextarea.editor.completers = [
  //     langTools.snippetCompleter,
  //     langTools.textCompleter,
  //     langTools.keyWordCompleter,
  //     customCompleter,
  //   ];

  //   queryBoxTextarea.editor.setOption(
  //     'enableBasicAutocompletion',
  //     true
  //   );

  //   queryBoxTextarea.editor.setOption(
  //     'enableLiveAutocompletion',
  //     nextProps.enabledLiveAutoComplete
  //   );
  // }

  // componentDidUpdate() {
  //   if (props.query.isExecuting && props.query.isDefaultSelect) {
  //     queryBoxTextarea.editor.focus();
  //     window.scrollTo(0, 0);
  //   }
  // }

  // componentWillUnmount() {
  //   queryBoxTextarea.editor.removeListener(
  //     EVENT_KEYS.onSelectionChange,
  //     onSelectionChange
  //   );
  // }

  const onSelectionChange=() =>{
    props.onSelectionChange(
      props.query.query,
      queryBoxTextarea.current.editor.getCopyText()
    );
  }

  const onExecQueryClick=() =>{
    const query =
      queryBoxTextarea.current.editor.getCopyText() || props.query.query;
    props.onExecQueryClick(query);
  }

  const onDiscQueryClick=()=> {
    props.onSQLChange('');
  }

  const onCancelQueryClick=()=> {
    props.onCancelQueryClick();
  }

  const onShowInfoClick=()=> {
    setState((state)=>({...state, infoModalVisible: true }));
  }


  const onWrapContentsChecked=()=> {
    setState((state)=>({...state, wrapEnabled: true }));
  }

  const onWrapContentsUnchecked=() =>{
    setState((state)=>({...state, wrapEnabled: false }));
  }

  const getQueryCompletions=(props)=> {
    const {
      databases,
      schemas,
      tables,
      columnsByTable,
      triggersByTable,
      indexesByTable,
      views,
      functions,
      procedures,
    } = props;

    const mapCompletionTypes = (items, type) => {
      let result = items;
      if (!Array.isArray(items)) {
        result = Object.keys(items || {}).reduce(
          (all, name) => all.concat(items[name]),
          []
        );
      }

      return (result || []).map(({ name }) => ({ name, type }));
    };

    return [
      ...mapCompletionTypes(databases, 'database'),
      ...mapCompletionTypes(schemas, 'schema'),
      ...mapCompletionTypes(tables, 'table'),
      ...mapCompletionTypes(columnsByTable, 'column'),
      ...mapCompletionTypes(triggersByTable, 'trigger'),
      ...mapCompletionTypes(indexesByTable, 'index'),
      ...mapCompletionTypes(views, 'view'),
      ...mapCompletionTypes(functions, 'function'),
      ...mapCompletionTypes(procedures, 'procedure'),
    ].map(({ name, type }) => ({ name, value: name, score: 1, meta: type }));
  }

  const getCommands=()=> {
    return [
      {
        name: 'increaseFontSize',
        bindKey: 'Ctrl-=|Ctrl-+',
        exec(editor) {
          const size = parseInt(editor.getFontSize(), 10) || 12;
          editor.setFontSize(size + 1);
        },
      },
      {
        name: 'decreaseFontSize',
        bindKey: 'Ctrl+-|Ctrl-_',
        exec(editor) {
          const size = parseInt(editor.getFontSize(), 10) || 12;
          editor.setFontSize(Math.max(size - 1 || 1));
        },
      },
      {
        name: 'resetFontSize',
        bindKey: 'Ctrl+0|Ctrl-Numpad0',
        exec(editor) {
          editor.setFontSize(12);
        },
      },
      {
        name: 'selectCurrentLine',
        bindKey: { win: 'Ctrl-L', mac: 'Command-L' },
        exec(editor) {
          const { row } = editor.selection.getCursor();
          const endColumn = editor.session.getLine(row).length;
          editor.selection.setSelectionRange({
            start: { column: 0, row },
            end: { column: endColumn, row },
          });
        },
      },
    ];
  }

  const focus=()=> {
    queryBoxTextarea.editor.focus();
  }


    const {
      widthOffset,
      client,
      query,
      onSaveToFileClick,
      onCopyToClipboardClick,
      onSQLChange,
      allowCancel,
    } = props;

    const infos = INFOS[client];
    // console.log(state.query_height);

    return (
      <div>
        <div id="acebox1">
            <AceEditor
              mode="sql"
              theme="clouds_midnight"
              name={props.editorName}
              height="100px"
              width="100%"
              ref={queryBoxTextarea}
              value={query.query}
              wrapEnabled={state.wrapEnabled}
              showPrintMargin={false}
              commands={getCommands()}
              editorProps={{ $blockScrolling: Infinity }}
              onChange={debounce(onSQLChange, 50)}
              enableBasicAutocompletion
              enableLiveAutocompletion
            />
            {
              // <div className="ui secondary menu" style={{ marginTop: 0 }}>
              //   <div className="right menu">
              //     <CheckBox
              //       name="wrapQueryContents"
              //       label="Wrap Contents"
              //       onChecked={onWrapContentsChecked}
              //       onUnchecked={onWrapContentsUnchecked} />
              //   </div>
              // </div>
            }
          <div className="ui secondary menu" style={{ marginTop: 0 }}>
            {infos && (
              <div className="item">
                <span>
                  <Button
                    className="ui icon Button small"
                    title="Query Information"
                    onClick={onShowInfoClick}
                  >
                    <i className="icon info" />
                  </Button>
                </span>
              </div>
            )}
              <Toolbar>
                <Button
                  className={`ui positive Button ${
                    query.isExecuting ? 'loading' : ''
                  }`}
                  onClick={onExecQueryClick}
                >
                  Execute
                </Button>
                {query.isExecuting && allowCancel ? (
                  <Button
                    className={`ui negative Button ${
                      query.isCanceling ? 'loading' : ''
                    }`}
                    onClick={onCancelQueryClick}
                  >
                    Cancel
                  </Button>
                ) : (
                  <Button
                    className="ui Button"
                    onClick={onDiscQueryClick}
                  >
                    Discard
                  </Button>
                )}
              </Toolbar>
            </div>
        </div>
        <QueryResult
          model={props.model}
          widthOffset={widthOffset}
          heigthOffset={state.query_height}
          onSaveToFileClick={onSaveToFileClick}
          onCopyToClipboardClick={onCopyToClipboardClick}
          resultItemsPerPage={query.resultItemsPerPage}
          copied={query.copied}
          saved={query.saved}
          query={query.queryHistory[query.queryHistory.length - 1]}
          results={query.results}
          isExecuting={query.isExecuting}
          error={query.error}
        />
        {state && state.infoModalVisible && (
          <ServerDBClientInfoModal
            infos={infos}
            client={client}
            onCloseClick={() => setState((state)=>({...state, infoModalVisible: false }))}
          />
        )}
        <style jsx="true">{`
          .ace_editor.ace_autocomplete .ace_completion-highlight {
            /* Avoid Blurry render of Highlighting in Retina display */
            text-shadow: 1px 0px 0px !important;
          }
          #acebox1 .react-resizable-handle {
            cursor: row-resize !important;
          }
        `}</style>
      </div>
    );
  }

